package com.cwt_taxi_xa.db.dal;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.cwt_taxi_xa.constants.SPConstants;
import com.cwt_taxi_xa.data.DataUtil;
import com.cwt_taxi_xa.model.LocalInfo;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.DateUtil;
import com.cwt_taxi_xa.util.ExceptionUtil;
import com.cwt_taxi_xa.util.SPUtils;
import com.cwt_taxi_xa.util.StringUtil;
import com.cwt_taxi_xa.util.Tools;

/**
 * 交易数据 数据解析类
 * 签到、签退、运营数据本地保存
 * @author wlh
 *
 */
public class LocalInfoDao {

	private DBOpenHelper helper;
	private ContentValues values;
	private static final String TAG = "LocalInfoDao";

	public LocalInfoDao(Context context) {
		super();
		helper = new DBOpenHelper(context);
		values = new ContentValues();
	}

	/**
	 * 保存交易数据
	 * @param info
	 * @return rowId 如果rowId ！= -1，则保存成功
	 */
	public synchronized long save(LocalInfo info) {
		try {
			SQLiteDatabase db = helper.getWritableDatabase();

			// 检查是否需要删除第一条数据
			int type = info.getType();
			int count = getCount(db, type);
			int largeSize = 0;
			if(type == LocalInfo.TYPE_BUSINESS){
				largeSize = 2000;
			}else if(type == LocalInfo.TYPE_CHECK_IN){
				largeSize = 2000;
			}else if(type == LocalInfo.TYPE_CHECK_OUT){
				largeSize = 2000;
			}else if(type == LocalInfo.TYPE_GPS){
				largeSize = 100000;
			}
			// 如果当前数量大于最大容量，则删除
			if(count > largeSize){
				deleteFirstInfoByType(db, type);
			}

			long rowId = -1;
			values.put(DBConstants.LOCAL_DATA, info.getData());
			values.put(DBConstants.LOCAL_STATUS, info.getStatus());
			values.put(DBConstants.LOCAL_TYPE, info.getType());

			String zgzh = null;

			if(info.getType() == LocalInfo.TYPE_BUSINESS){
				String data = info.getData();
				byte[] dataByte = Tools.yxReversal(Tools.parseHexStr2Byte(data));

				int zgzhIndex = 13 + 25 + 25 + 15 + 6 + 16;
				int carTimesIndex = 13 + 25 + 25 + 15 + 6 + 16 + 19 + 20;
				int sTimeIndex = 13 + 25 + 25 + 15 + 6 + 16 + 19;

				int carTimes = Integer.parseInt(Tools.parseByte2HexStr(Tools.byteTobyte(dataByte, carTimesIndex, 4)), 16);
				values.put(DBConstants.LOCAL_CAR_TIMES, ""+carTimes);

				//驾驶员从业资格证号	BYTE[19]
				zgzh = Tools.byteToString(dataByte, zgzhIndex, 19);

				// 上车时间	BCD[5]	格式为YY-MM-DD-hh-mm
				String sTime = Tools.bcd2Str(Tools.byteTobyte(dataByte, sTimeIndex, 5));
				//yyMMddHHmmss
				String time = sTime + "00";
				String date = DateUtil.getTime(time, DateUtil.df8, DateUtil.df9);
				info.setTime(time);
				info.setDate(date);
				AppLog.i(TAG, "营运数据--车次："+carTimes+"; 开始时间："
						+sTime+";date:"+date+";time:"+time+";zgzh:"+zgzh);
			}else if(info.getType() == LocalInfo.TYPE_CHECK_OUT){
				String data = info.getData();
				byte[] dataByte = Tools.yxReversal(Tools.parseHexStr2Byte(data));

				int zgzhIndex = 13 + 25 + 16;
				int powerOnTimeIndex = 13 + 25 + 16 + 19 + 8;
				int powerOffTimeIndex = 13 + 25 + 16 + 19 + 8 + 6;

				//驾驶员从业资格证号	BYTE[19],54字节开始
				zgzh = Tools.byteToString(dataByte, zgzhIndex, 19);

				// 当班开机时间	BCD[6]	格式为YYYYMMDDhhmm
				String powerOnTime = Tools.bcd2Str(Tools.byteTobyte(dataByte, powerOnTimeIndex, 6));
				values.put(DBConstants.LOCAL_METER_CODE, powerOnTime);

				// 当班关机时间	BCD[6]	格式为YYYYMMDDhhmm
				String powerOffTime = Tools.bcd2Str(Tools.byteTobyte(dataByte, powerOffTimeIndex, 6));
				values.put(DBConstants.LOCAL_CAR_TIMES, powerOffTime);

				powerOffTime = powerOffTime + "00";
				String time = DateUtil.getTime(powerOffTime, DateUtil.df6, DateUtil.df8);
				String date = DateUtil.getTime(powerOffTime, DateUtil.df6, DateUtil.df9);
				info.setTime(time);
				info.setDate(date);
				AppLog.i(TAG, "签退数据--开机："+powerOnTime+"; 关机时间："+powerOffTime+
						";date:"+date+";time:"+time+";zgzh:"+zgzh);
			}else if(info.getType() == LocalInfo.TYPE_CHECK_IN){
				String data = info.getData();
				byte[] dataByte = Tools.yxReversal(Tools.parseHexStr2Byte(data));

				int zgzhIndex = 13+25+16;
				int powerTimeIndex = 13+25+16 + 19 + 6;

				//驾驶员从业资格证号	BYTE[19],54字节开始
				zgzh = Tools.byteToString(dataByte, zgzhIndex, 19);

				//开机时间	BYTE[6]	YYYYMMDDHHNN
				String powerOnTime = Tools.bcd2Str(Tools.byteTobyte(dataByte, powerTimeIndex, 6));

				powerOnTime = powerOnTime + "00";
				String time = DateUtil.getTime(powerOnTime, DateUtil.df6, DateUtil.df8);
				String date = DateUtil.getTime(powerOnTime, DateUtil.df6, DateUtil.df9);
				info.setTime(time);
				info.setDate(date);

				AppLog.i(TAG, "签到数据--zgzh:"+zgzh);
			}

			String time = info.getTime();
			if(StringUtil.isNull(time)){
				time = DateUtil.getTodayDate(DateUtil.df8);
			}
			values.put(DBConstants.LOCAL_TIME, time);
			String date = info.getDate();
			if(StringUtil.isNull(date)){
				date = DateUtil.getTodayDate(DateUtil.df9);
			}
			values.put(DBConstants.LOCAL_DATE, date);
			if(StringUtil.isNull(zgzh)){
				zgzh = DataUtil.getDriverCode();
			}
			if(!StringUtil.isNull(zgzh)){
				values.put(DBConstants.DRIVER_CERTIFICATE_CODE, zgzh);
			}
			rowId = db.insert(DBConstants.TABLE_LOCAL, null, values);
			db.close();
			AppLog.i(TAG, "插入一条本地数据，rowId："+rowId+"; type:"+info.getType());
			return rowId;
		} catch (Exception e) {
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return -1;
		}
	}

	/**
	 * 查找信息
	 * @return locationInfos 所有数据
	 */
	public synchronized ArrayList<LocalInfo> findByType(int type, int currentPage, int pageCount) {
		// TODO Auto-generated method stub
		try {
			ArrayList<LocalInfo> infos = null;
			SQLiteDatabase db = helper.getReadableDatabase();
			String selection = "";
			String zgzh = DataUtil.getDriverCode();
			if(type == LocalInfo.TYPE_BUSINESS  && !StringUtil.isNull(zgzh)){
				selection = DBConstants.LOCAL_TYPE+" = "+ type+" order by "+ DBConstants.LOCAL_TIME+" desc limit "+
						((currentPage-1)*pageCount)+","+pageCount;
//				selection = DBConstants.LOCAL_TYPE+" = "+ type+" and "+DBConstants.DRIVER_CERTIFICATE_CODE+
//						" = '"+zgzh+ "' order by "+ DBConstants.LOCAL_TIME+" desc limit "+
//						((currentPage-1)*pageCount)+","+pageCount;
			}else{
				selection = DBConstants.LOCAL_TYPE+" = "+ type+" order by "+
						DBConstants.LOCAL_ID+" desc limit "+((currentPage-1)*pageCount)+","+pageCount;
//				selection = DBConstants.LOCAL_TYPE+" = "+ type+" order by "+
//						DBConstants.LOCAL_ID+" desc limit "+((currentPage-1)*pageCount)+","+pageCount;
			}
			Cursor c = db.query(DBConstants.TABLE_LOCAL, null, selection,
					null, null, null,null);
			if(c != null){
				infos = new ArrayList<LocalInfo>();
				while(c.moveToNext()){
					LocalInfo info = new LocalInfo();
					info.setData(c.getString(c.getColumnIndex(DBConstants.LOCAL_DATA)));
					info.setTime(c.getString(c.getColumnIndex(DBConstants.LOCAL_TIME)));
					info.setMsgId(c.getInt(c.getColumnIndex(DBConstants.LOCAL_ID)));
					info.setStatus(c.getInt(c.getColumnIndex(DBConstants.LOCAL_STATUS)));
					info.setType(type);
					infos.add(info);
				}
			}
			db.close();
			return infos;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return null;
		}
	}

	/**
	 * 查找信息
	 * @return locationInfos 所有数据
	 */
	public synchronized ArrayList<LocalInfo> findByType(int type) {
		// TODO Auto-generated method stub
		try {
			ArrayList<LocalInfo> infos = null;
			SQLiteDatabase db = helper.getReadableDatabase();
			Cursor c = db.query(DBConstants.TABLE_LOCAL, null, DBConstants.LOCAL_TYPE+"=?",
					new String[]{String.valueOf(type)}, null, null,null);
			if(c != null){
				infos = new ArrayList<LocalInfo>();
				while(c.moveToNext()){
					LocalInfo info = new LocalInfo();
					info.setData(c.getString(c.getColumnIndex(DBConstants.LOCAL_DATA)));
					info.setTime(c.getString(c.getColumnIndex(DBConstants.LOCAL_TIME)));
					info.setMsgId(c.getInt(c.getColumnIndex(DBConstants.LOCAL_ID)));
					info.setStatus(c.getInt(c.getColumnIndex(DBConstants.LOCAL_STATUS)));
					info.setType(type);
					infos.add(info);
				}
			}
			db.close();
			return infos;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return null;
		}
	}

	/**
	 * 查找信息
	 * @return locationInfos 当前营运数据
	 */
	public synchronized ArrayList<LocalInfo> getOneDayBusinessInfo(String date) {
		// TODO Auto-generated method stub
		try {
			String zgzh = DataUtil.getDriverCode();
			if(StringUtil.isNull(zgzh)){
				return null;
			}

			ArrayList<LocalInfo> infos = null;
			SQLiteDatabase db = helper.getReadableDatabase();

			//怀疑因为司机号不对查不出数据

//			String selection = DBConstants.LOCAL_TYPE+" = "+
//					LocalInfo.TYPE_BUSINESS+" and "+
//					DBConstants.DRIVER_CERTIFICATE_CODE+
//					" = '"+zgzh+"' and "+DBConstants.LOCAL_DATE+
//					" = "+date+ " order by "+ DBConstants.LOCAL_TIME+" desc";


			String selection = DBConstants.LOCAL_TYPE+" = "+
					LocalInfo.TYPE_BUSINESS+" and "+DBConstants.LOCAL_DATE+
					" = "+date+ " order by "+ DBConstants.LOCAL_TIME+" desc";

//			String selection = DBConstants.LOCAL_TYPE+" = "+
//					LocalInfo.TYPE_BUSINESS+" order by "+ DBConstants.LOCAL_TIME+" desc";

//			AppLog.e("运营数据不准测试---查询语句："+selection);

			Cursor c = db.query(DBConstants.TABLE_LOCAL, null, selection,
					null, null, null,null);
			if(c != null){
				infos = new ArrayList<LocalInfo>();
				while(c.moveToNext()){
					LocalInfo info = new LocalInfo();
					info.setData(c.getString(c.getColumnIndex(DBConstants.LOCAL_DATA)));
					info.setTime(c.getString(c.getColumnIndex(DBConstants.LOCAL_TIME)));
					info.setMsgId(c.getInt(c.getColumnIndex(DBConstants.LOCAL_ID)));
					info.setStatus(c.getInt(c.getColumnIndex(DBConstants.LOCAL_STATUS)));

//					AppLog.e("运营数据不准测试---查询："+info.getTime());
//					AppLog.e("运营数据不准测试---查询："+info.getMsgId());
//					AppLog.e("运营数据不准测试---查询："+info.getStatus());

					/*info.setMeterCode(c.getString(c.getColumnIndex(DBConstants.LOCAL_METER_CODE)));
					info.setCarTimes(c.getString(c.getColumnIndex(DBConstants.LOCAL_CAR_TIMES)));*/
					infos.add(info);
				}
			}
			db.close();
			return infos;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return null;
		}
	}

	/**
	 * 查找信息
	 * @return locationInfos 当前营运数据
	 */
	public synchronized ArrayList<LocalInfo> getOneDayBusinessInfo2(String date) {
		// TODO Auto-generated method stub
		try {
			String zgzh = DataUtil.getDriverCode();
			if(StringUtil.isNull(zgzh)){
				return null;
			}

			ArrayList<LocalInfo> infos = null;
			SQLiteDatabase db = helper.getReadableDatabase();

			//怀疑因为司机号不对查不出数据
			String selection = DBConstants.LOCAL_TYPE+" = "+ LocalInfo.TYPE_BUSINESS+" and "+
					DBConstants.DRIVER_CERTIFICATE_CODE+" = '"+zgzh+"' and "+
					DBConstants.LOCAL_DATE+" = "+date+
					" order by "+ DBConstants.LOCAL_TIME+" desc";


			//怀疑因为司机号不对查不出数据
			selection = DBConstants.LOCAL_TYPE+" = "+ LocalInfo.TYPE_BUSINESS+" and "+
					DBConstants.LOCAL_DATE+" = "+date+
					" order by "+ DBConstants.LOCAL_TIME+" desc";


			//改成获取所有数据再根据车次筛选
			selection = DBConstants.LOCAL_TYPE+" = "+ LocalInfo.TYPE_BUSINESS;



//			String selection = DBConstants.LOCAL_TYPE+" = "+
//					LocalInfo.TYPE_BUSINESS+" order by "+ DBConstants.LOCAL_TIME+" desc";

//			AppLog.e("运营数据不准测试---查询语句："+selection);

			Cursor c = db.query(DBConstants.TABLE_LOCAL, null, selection,
					null, null, null,null);
			if(c != null){
				infos = new ArrayList<LocalInfo>();
				int firstcartimes = SPUtils.getParamInteger(SPConstants.SPK_cartimes, SPConstants.SPV_cartimes);
				while(c.moveToNext()){

					if(c.getInt(c.getColumnIndex(DBConstants.LOCAL_CAR_TIMES))>=firstcartimes){
						LocalInfo info = new LocalInfo();
						info.setData(c.getString(c.getColumnIndex(DBConstants.LOCAL_DATA)));
						info.setTime(c.getString(c.getColumnIndex(DBConstants.LOCAL_TIME)));
						info.setMsgId(c.getInt(c.getColumnIndex(DBConstants.LOCAL_ID)));
						info.setStatus(c.getInt(c.getColumnIndex(DBConstants.LOCAL_STATUS)));

//					AppLog.e("运营数据不准测试---查询："+info.getTime());
//					AppLog.e("运营数据不准测试---查询："+info.getMsgId());
//					AppLog.e("运营数据不准测试---查询："+info.getStatus());
//					AppLog.e("运营数据不准测试---查询："+c.getInt(c.getColumnIndex(DBConstants.LOCAL_CAR_TIMES)));

						/*info.setMeterCode(c.getString(c.getColumnIndex(DBConstants.LOCAL_METER_CODE)));
					info.setCarTimes(c.getString(c.getColumnIndex(DBConstants.LOCAL_CAR_TIMES)));*/
						infos.add(info);
					}

				}
			}
			db.close();
			return infos;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return null;
		}
	}

	/**
	 * 查找信息
	 * @return locationInfos 当前营运数据
	 */
	public synchronized ArrayList<LocalInfo> get7daysBusinessInfo() {
		// TODO Auto-generated method stub
		try {
			String zgzh = DataUtil.getDriverCode();
			if(StringUtil.isNull(zgzh)){
				return null;
			}

			ArrayList<LocalInfo> infos = new ArrayList<LocalInfo>();
			SQLiteDatabase db = helper.getReadableDatabase();
			Calendar calendar = Calendar.getInstance();
			long time = DateUtil.df6.parse(DateUtil.getTodayDate(DateUtil.df6)).getTime();
			calendar.setTimeInMillis(time);
			int year = calendar.get(Calendar.YEAR);
			int month = calendar.get(Calendar.MONTH);
			int day = calendar.get(Calendar.DAY_OF_MONTH);

			for(int i = 0;i<7;i++){
				calendar.set(year, month, day-i);
				Date date = calendar.getTime();
				String dateStr = DateUtil.df9.format(date);

//				String selection = DBConstants.LOCAL_TYPE+" = "+ LocalInfo.TYPE_BUSINESS+" and "+DBConstants.DRIVER_CERTIFICATE_CODE+
//						" = '"+zgzh+"' and "+DBConstants.LOCAL_DATE+
//						" = "+dateStr+ " order by "+ DBConstants.LOCAL_ID;
				String selection = DBConstants.LOCAL_TYPE+" = "+ LocalInfo.TYPE_BUSINESS+
						" and "+DBConstants.LOCAL_DATE+
						" = "+dateStr+ " order by "+ DBConstants.LOCAL_ID;
				Cursor c = db.query(DBConstants.TABLE_LOCAL, null, selection,
						null, null, null,null);
				if(c != null){
					while(c.moveToNext()){
						LocalInfo info = new LocalInfo();
						info.setData(c.getString(c.getColumnIndex(DBConstants.LOCAL_DATA)));
						info.setTime(c.getString(c.getColumnIndex(DBConstants.LOCAL_TIME)));
						info.setMsgId(c.getInt(c.getColumnIndex(DBConstants.LOCAL_ID)));
						info.setStatus(c.getInt(c.getColumnIndex(DBConstants.LOCAL_STATUS)));
						infos.add(info);
					}
				}
			}
			db.close();
			return infos;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return null;
		}
	}

	/**
	 * 查找信息
	 * @return locationInfos 所有数据
	 */
	public synchronized ArrayList<LocalInfo> findByType(int type, int postStatus, String sTime, String eTime) {
		// TODO Auto-generated method stub
		try {
			ArrayList<LocalInfo> infos = null;
			SQLiteDatabase db = helper.getReadableDatabase();
			/*Cursor c = db.query(DBConstants.TABLE_LOCAL, null, DBConstants.LOCAL_TYPE+"=?",
					new String[]{String.valueOf(type)}, null, null,null);*/
			/*String sql = "select count(*) from "+DBConstants.TABLE_LOCAL+" where "+
					DBConstants.LOCAL_TYPE+" = '"+type+"'";
			if(postStatus != -1){
				sql = sql + " and"+ DBConstants.LOCAL_STATUS+" = "+postStatus;

			}
			Cursor c = db.rawQuery(sql, null);*/
			String sql = DBConstants.LOCAL_TYPE+" = "+type;
			if(postStatus != -1){
				sql = sql + " and "+ DBConstants.LOCAL_STATUS+" = "+postStatus;
			}
			Cursor c = db.query(DBConstants.TABLE_LOCAL, null, sql,
					null, null, null, null);
			if(c != null){
				// 是否需要时间筛选
				boolean select = false;
				AppLog.i(TAG, "筛选本地数据sTime:"+sTime+"; eTime:"+eTime);
				long sTimeCode = Long.parseLong(sTime);
				long eTimeCode = Long.parseLong(eTime);
				if(sTimeCode != 0 && eTimeCode != 0){
					select = true;
				}
				infos = new ArrayList<LocalInfo>();
				while(c.moveToNext()){
					if(select){
						String time = c.getString(c.getColumnIndex(DBConstants.LOCAL_TIME));
						boolean isPassed = DateUtil.isBetweenDate1AndDate2(DateUtil.df8, sTime, eTime, time);
						if(isPassed){
							LocalInfo info = new LocalInfo();
							info.setStatus(c.getInt(c.getColumnIndex(DBConstants.LOCAL_STATUS)));
							info.setMsgId(c.getInt(c.getColumnIndex(DBConstants.LOCAL_ID)));
							info.setData(c.getString(c.getColumnIndex(DBConstants.LOCAL_DATA)));
							info.setCarTimes(c.getString(c.getColumnIndex(DBConstants.LOCAL_CAR_TIMES)));
							info.setMeterCode(c.getString(c.getColumnIndex(DBConstants.LOCAL_METER_CODE)));
							info.setTime(time);
							info.setType(type);
							infos.add(info);
						}
					}else{
						LocalInfo info = new LocalInfo();
						info.setStatus(c.getInt(c.getColumnIndex(DBConstants.LOCAL_STATUS)));
						info.setMsgId(c.getInt(c.getColumnIndex(DBConstants.LOCAL_ID)));
						info.setData(c.getString(c.getColumnIndex(DBConstants.LOCAL_DATA)));
						info.setTime(c.getString(c.getColumnIndex(DBConstants.LOCAL_TIME)));
						info.setCarTimes(c.getString(c.getColumnIndex(DBConstants.LOCAL_CAR_TIMES)));
						info.setMeterCode(c.getString(c.getColumnIndex(DBConstants.LOCAL_METER_CODE)));
						info.setType(type);
						infos.add(info);
					}
				}
			}
			db.close();
			return infos;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return null;
		}
	}

	/**
	 * 查找信息
	 * @return locationInfos 所有数据
	 */
	public synchronized LocalInfo findLastNoPostByType(int type) {
		// TODO Auto-generated method stub
		try {
			LocalInfo info = null;
			SQLiteDatabase db = helper.getReadableDatabase();
			/*Cursor c = db.query(DBConstants.TABLE_LOCAL, null, DBConstants.LOCAL_TYPE+"=?",
					new String[]{String.valueOf(type)}, null, null,null);*/
			String sql = DBConstants.LOCAL_STATUS+" = 0 and "+
					DBConstants.LOCAL_TYPE+" = "+type+
					" and "+DBConstants.LOCAL_DATE +" not like '1970%'" +
					" and "+DBConstants.LOCAL_DATE +" not like '2070%'";
			if(type == LocalInfo.TYPE_CHECK){
				sql = DBConstants.LOCAL_STATUS+" = 0 and "+DBConstants.LOCAL_TYPE+" != "+LocalInfo.TYPE_BUSINESS
						+" and "+DBConstants.LOCAL_TYPE+" != "+LocalInfo.TYPE_GPS+
						" and "+DBConstants.LOCAL_DATE +" not like '1970%'" +
						" and "+DBConstants.LOCAL_DATE +" not like '2070%'";
			}
			Cursor c = db.query(DBConstants.TABLE_LOCAL, null, sql,
					null, null, null, null);
			if(c != null && c.moveToFirst()){
				info = new LocalInfo();
				info.setData(c.getString(c.getColumnIndex(DBConstants.LOCAL_DATA)));
				info.setMsgId(c.getInt(c.getColumnIndex(DBConstants.LOCAL_ID)));
				info.setStatus(c.getInt(c.getColumnIndex(DBConstants.LOCAL_STATUS)));
				info.setTime(c.getString(c.getColumnIndex(DBConstants.LOCAL_TIME)));
				info.setType(c.getInt(c.getColumnIndex(DBConstants.LOCAL_TYPE)));
				//				AppLog.i(TAG, "本地数据: id:"+info.getMsgId()+"；上传状态："+info.getStatus()+"; 类型："+info.getType());
				//				AppLog.i(TAG, "本地数据: 数据:"+info.getData());

			}
			db.close();
			return info;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return null;
		}
	}

	/**
	 * 查找最新的考勤信息
	 * @return locationInfos 所有数据
	 */
	public synchronized LocalInfo findLastCheckInfo() {
		// TODO Auto-generated method stub
		try {
			LocalInfo info = null;
			SQLiteDatabase db = helper.getReadableDatabase();
			/*Cursor c = db.query(DBConstants.TABLE_LOCAL, null, DBConstants.LOCAL_TYPE+"=?",
					new String[]{String.valueOf(type)}, null, null,null);*/
			/*String sql = DBConstants.LOCAL_TYPE+" != "+LocalInfo.TYPE_BUSINESS
					+" and "+DBConstants.LOCAL_TYPE+" != "+LocalInfo.TYPE_GPS;
			Cursor c = db.query(DBConstants.TABLE_LOCAL, null, sql,
					null, null, null, null);*/
			/*Cursor c = db.query(DBConstants.TABLE_LOCAL, null, DBConstants.LOCAL_TYPE+"=?",
					new String[]{String.valueOf(LocalInfo.TYPE_CHECK_IN)}, null, null,null);*/
			String sql = DBConstants.LOCAL_TYPE+" = "+LocalInfo.TYPE_CHECK_IN + " and "+
					DBConstants.LOCAL_DATE +" not like '1970%'" + " and "+DBConstants.LOCAL_DATE +" not like '2070%'";
			Cursor c = db.query(DBConstants.TABLE_LOCAL, null, sql,
					null, null, null, null);
			if(c != null && c.moveToLast()){
				info = new LocalInfo();
				info.setData(c.getString(c.getColumnIndex(DBConstants.LOCAL_DATA)));
				info.setMsgId(c.getInt(c.getColumnIndex(DBConstants.LOCAL_ID)));
				info.setStatus(c.getInt(c.getColumnIndex(DBConstants.LOCAL_STATUS)));
				info.setTime(c.getString(c.getColumnIndex(DBConstants.LOCAL_TIME)));
				info.setType(c.getInt(c.getColumnIndex(DBConstants.LOCAL_TYPE)));
				//				AppLog.i(TAG, "本地数据: id:"+info.getMsgId()+"；上传状态："+info.getStatus()+"; 类型："+info.getType());
				//				AppLog.i(TAG, "本地数据: 数据:"+info.getData());

			}
			db.close();
			return info;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return null;
		}
	}

	/**
	 * 查找最新的营运数据
	 * @return locationInfos 所有数据
	 */
	public synchronized LocalInfo findLastBusinessInfo() {
		// TODO Auto-generated method stub
		try {
			LocalInfo info = null;
			SQLiteDatabase db = helper.getReadableDatabase();
			Cursor c = db.query(DBConstants.TABLE_LOCAL, null, DBConstants.LOCAL_TYPE+"=?",
					new String[]{String.valueOf(LocalInfo.TYPE_BUSINESS)}, null, null,null);
			if(c != null && c.moveToLast()){
				info = new LocalInfo();
				info.setData(c.getString(c.getColumnIndex(DBConstants.LOCAL_DATA)));
				info.setMsgId(c.getInt(c.getColumnIndex(DBConstants.LOCAL_ID)));
				info.setStatus(c.getInt(c.getColumnIndex(DBConstants.LOCAL_STATUS)));
				info.setTime(c.getString(c.getColumnIndex(DBConstants.LOCAL_TIME)));
				info.setDate(c.getString(c.getColumnIndex(DBConstants.LOCAL_DATE)));
				info.setMeterCode(c.getString(c.getColumnIndex(DBConstants.LOCAL_METER_CODE)));
				info.setCarTimes(c.getString(c.getColumnIndex(DBConstants.LOCAL_CAR_TIMES)));
				info.setType(c.getInt(c.getColumnIndex(DBConstants.LOCAL_TYPE)));
			}
			db.close();
			return info;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return null;
		}
	}

	/**
	 * 查找第一条信息
	 * @return locationInfos 所有数据
	 */
	public synchronized LocalInfo findFirstInfoByType(int type) {
		// TODO Auto-generated method stub
		try {
			LocalInfo info = null;
			SQLiteDatabase db = helper.getReadableDatabase();
			/*Cursor c = db.query(DBConstants.TABLE_LOCAL, null, DBConstants.LOCAL_TYPE+"=?",
					new String[]{String.valueOf(type)}, null, null,null);*/
			String sql = DBConstants.LOCAL_TYPE+" = "+type;
			Cursor c = db.query(DBConstants.TABLE_LOCAL, null, sql,
					null, null, null, null);
			if(c != null && c.moveToFirst()){
				info = new LocalInfo();
				info.setData(c.getString(c.getColumnIndex(DBConstants.LOCAL_DATA)));
				info.setMsgId(c.getInt(c.getColumnIndex(DBConstants.LOCAL_ID)));
				info.setStatus(c.getInt(c.getColumnIndex(DBConstants.LOCAL_STATUS)));
				info.setTime(c.getString(c.getColumnIndex(DBConstants.LOCAL_TIME)));
				info.setCarTimes(c.getString(c.getColumnIndex(DBConstants.LOCAL_CAR_TIMES)));
				info.setType(c.getInt(c.getColumnIndex(DBConstants.LOCAL_TYPE)));
				//				AppLog.i(TAG, "本地数据: id:"+info.getMsgId()+"；上传状态："+info.getStatus()+"; 类型："+info.getType());
				//				AppLog.i(TAG, "本地数据: 数据:"+info.getData());

			}
			db.close();
			return info;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return null;
		}
	}

	/**
	 * 删除第一条信息
	 * @return locationInfos 所有数据
	 */
	public synchronized void deleteFirstInfoByType(SQLiteDatabase db, int type) {
		// TODO Auto-generated method stub
		try {
			String sql = DBConstants.LOCAL_TYPE+" = "+type;
			Cursor c = db.query(DBConstants.TABLE_LOCAL, null, sql,
					null, null, null, null);
			if(c != null && c.moveToFirst()){
				int id = c.getInt(c.getColumnIndex(DBConstants.LOCAL_ID));
				int result = db.delete(DBConstants.TABLE_LOCAL,
						DBConstants.LOCAL_ID+"=?", new String[]{String.valueOf(id)});
				AppLog.i(TAG, "删除第一条数据：result = "+result + "; id = "+id+"; type = "+type);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
		}
	}

	/**
	 * 查找未上传GPS信息，最大8条
	 * @return locationInfos 所有数据
	 */
	public synchronized ArrayList<LocalInfo> getNoPostGpsInfos() {
		// TODO Auto-generated method stub
		try {
			ArrayList<LocalInfo> infos = null;
			SQLiteDatabase db = helper.getReadableDatabase();
			String sql = DBConstants.LOCAL_STATUS+" = 0 and "+DBConstants.LOCAL_TYPE+" = "+LocalInfo.TYPE_GPS;
			Cursor c = db.query(DBConstants.TABLE_LOCAL, null, sql,
					null, null, null, null);
			if(c != null){
				infos = new ArrayList<LocalInfo>();
				int count = 0;
				while(c.moveToNext() && count < 8){

					LocalInfo info = new LocalInfo();
					String data = c.getString(c.getColumnIndex(DBConstants.LOCAL_DATA));
					if(!StringUtil.isNull(data)){
						data = data.substring(0, 50);
					}
					info.setData(data);
					info.setMsgId(c.getInt(c.getColumnIndex(DBConstants.LOCAL_ID)));
					info.setStatus(c.getInt(c.getColumnIndex(DBConstants.LOCAL_STATUS)));
					info.setTime(c.getString(c.getColumnIndex(DBConstants.LOCAL_TIME)));
					info.setType(c.getInt(c.getColumnIndex(DBConstants.LOCAL_TYPE)));
					infos.add(info);
					count ++;
					AppLog.i(TAG, "本地数据：gps数据上传；"+info.getData());
				}
			}
			db.close();
			return infos;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return null;
		}
	}

	/**
	 * 查找信息
	 * @return locationInfos 所有数据
	 */
	public synchronized ArrayList<LocalInfo> findNoPostByType(int type) {
		// TODO Auto-generated method stub
		try {
			ArrayList<LocalInfo> infos = null;
			SQLiteDatabase db = helper.getReadableDatabase();
			/*Cursor c = db.query(DBConstants.TABLE_LOCAL, null, DBConstants.LOCAL_TYPE+"=?",
					new String[]{String.valueOf(type)}, null, null,null);*/
			String sql = DBConstants.LOCAL_STATUS+" = 0 and "+DBConstants.LOCAL_TYPE+" = "+type;
			Cursor c = db.query(DBConstants.TABLE_LOCAL, null, sql,
					null, null, null, null);
			if(c != null){
				infos = new ArrayList<LocalInfo>();
				while(c.moveToNext()){
					LocalInfo info = new LocalInfo();
					info.setData(c.getString(c.getColumnIndex(DBConstants.LOCAL_DATA)));
					info.setMsgId(c.getInt(c.getColumnIndex(DBConstants.LOCAL_ID)));
					info.setStatus(c.getInt(c.getColumnIndex(DBConstants.LOCAL_STATUS)));
					info.setTime(c.getString(c.getColumnIndex(DBConstants.LOCAL_TIME)));
					info.setType(type);
					infos.add(info);
				}
			}
			db.close();
			return infos;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return null;
		}
	}

	/**
	 * 通过计价器号和车次查找营运数据
	 * @return locationInfos 所有数据
	 */
	public synchronized boolean isBusinessInfoExitByMeterAndCarTimes(SQLiteDatabase db, String meterCode, int carTimes) {
		// TODO Auto-generated method stub
		boolean exit = false;
		try {
			String selection = DBConstants.LOCAL_TYPE+" = "+ LocalInfo.TYPE_BUSINESS+" and "+DBConstants.LOCAL_METER_CODE+
					" = '"+meterCode+"' and "+DBConstants.LOCAL_CAR_TIMES+
					" = '"+carTimes+ "' order by "+ DBConstants.LOCAL_ID;
			Cursor c = db.query(DBConstants.TABLE_LOCAL, null, selection,
					null, null, null,null);
			if(c != null){
				int count = c.getCount();
				if(count > 0){
					exit = true;
				}
			}
			return exit;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return exit;
		}
	}

	/**
	 * 通过计价器号和车次查找营运数据
	 * @return locationInfos 所有数据
	 */
	public synchronized LocalInfo findBusinessInfoByMeterAndCarTimes(String meterCode, int carTimes) {
		// TODO Auto-generated method stub
		try {
			LocalInfo info = null;
			SQLiteDatabase db = helper.getReadableDatabase();
			String selection = DBConstants.LOCAL_TYPE+" = "+ LocalInfo.TYPE_BUSINESS+" and "+DBConstants.LOCAL_METER_CODE+
					" = '"+meterCode+"' and "+DBConstants.LOCAL_CAR_TIMES+
					" = '"+carTimes+ "' order by "+ DBConstants.LOCAL_ID;
			Cursor c = db.query(DBConstants.TABLE_LOCAL, null, selection,
					null, null, null,null);
			if(c != null && c.moveToLast()){
				info = new LocalInfo();
				info.setStatus(c.getInt(c.getColumnIndex(DBConstants.LOCAL_STATUS)));
			}
			db.close();
			return info;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return null;
		}
	}

	/**
	 * 通过计价器号和车次查找营运数据
	 * @return locationInfos 所有数据
	 */
	public synchronized void delBusinessInfoByMeterAndCarTimes(String meterCode, int carTimes) {
		// TODO Auto-generated method stub
		try {
			SQLiteDatabase db = helper.getReadableDatabase();
			String selection = DBConstants.LOCAL_TYPE+" = "+ LocalInfo.TYPE_BUSINESS+" and "+DBConstants.LOCAL_METER_CODE+
					" = '"+meterCode+"' and "+DBConstants.LOCAL_CAR_TIMES+
					" = '"+carTimes+ "' order by "+ DBConstants.LOCAL_ID;
			Cursor c = db.query(DBConstants.TABLE_LOCAL, null, selection,
					null, null, null,null);
			if(c != null && c.moveToLast()){
				int id = c.getInt(c.getColumnIndex(DBConstants.LOCAL_ID));
				int result = db.delete(DBConstants.TABLE_LOCAL,
						DBConstants.LOCAL_ID+"=?", new String[]{String.valueOf(id)});
				AppLog.i(TAG, "删除营运数据：id:"+id+"; result："+result+"; carTimes:"+carTimes);
			}
			db.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
		}
	}

	/**
	 * 获取数据总条数
	 * @param db2
	 * @return count 总条数 count != -1：成功
	 */
	public synchronized int getCount(SQLiteDatabase db, int type){
		int count = -1;
		Cursor c = db.query(DBConstants.TABLE_LOCAL, null, DBConstants.LOCAL_TYPE+"=?",
				new String[]{String.valueOf(type)}, null, null,null);
		if(c != null){
			count = c.getCount();
		}
		return count;
	}

	/**
	 * 获取未上传数据总条数
	 * @param db2
	 * @return count 总条数 count != -1：成功
	 */
	public synchronized int getNoPostCount(int type){
		SQLiteDatabase db = helper.getReadableDatabase();
		String sql = "select count(*) from "+DBConstants.TABLE_LOCAL+
				" where "+DBConstants.LOCAL_STATUS+" = 0 and "+DBConstants.LOCAL_TYPE+" ="+type;
		Cursor c = db.rawQuery(sql, null);
		c.moveToFirst();
		int count = c.getInt(0);
		db.close();
		return count;
	}

	/**
	 * 清空表数据
	 * @return result != -1：成功
	 */
	public synchronized int clearTable(){
		try {
			int result = -1;
			SQLiteDatabase db = helper.getWritableDatabase();
			result = db.delete(DBConstants.TABLE_LOCAL, null, null);
			//		db.execSQL("delete from sqlite_sequence where name = \"" + Constants.TABLENAME+ "\"");
			db.execSQL("update sqlite_sequence set seq = 0 where name = \""+ DBConstants.TABLE_LOCAL+ "\"");
			db.close();
			AppLog.i(TAG, "清空表数据,result:"+result);
			return result;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return -1;
		}
	}

	public synchronized int getCount(int type) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = helper.getWritableDatabase();
		int count = getCount(db, type);
		db.close();
		return count;
	}

	public synchronized int getBusinessCount() {
		// TODO Auto-generated method stub
		String zgzh = DataUtil.getDriverCode();
		if(StringUtil.isNull(zgzh)){
			return 0;
		}
		int count = -1;
		SQLiteDatabase db = helper.getReadableDatabase();

		String selection = "";

		selection = DBConstants.LOCAL_TYPE+" = "+ LocalInfo.TYPE_BUSINESS;


//		String selection = DBConstants.LOCAL_TYPE+" = "+ LocalInfo.TYPE_BUSINESS+" and "+DBConstants.DRIVER_CERTIFICATE_CODE+
//				" = '"+zgzh+"'";
		Cursor c = db.query(DBConstants.TABLE_LOCAL, null, selection,
				null, null, null,null);
		if(c != null){
			count = c.getCount();
		}
		return count;
	}

	public synchronized int deleteInfo(int id) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = helper.getWritableDatabase();
		int result = -1;
		Cursor c = db.query(DBConstants.TABLE_LOCAL, null, DBConstants.LOCAL_ID+"=?",
				new String[]{String.valueOf(id)}, null, null,null);
		if(c != null){
			while(c.moveToNext() && c.isFirst()){
				result = db.delete(DBConstants.TABLE_LOCAL,
						DBConstants.LOCAL_ID+"=?", new String[]{String.valueOf(id)});
			}
		}
		AppLog.i(TAG, "删除一条交易数据，result:"+result);
		return result;
	}

	public synchronized int updateStatus(int id) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = helper.getWritableDatabase();
		int result = -1;
		Cursor c = db.query(DBConstants.TABLE_LOCAL, null, DBConstants.LOCAL_ID+"=?",
				new String[]{String.valueOf(id)}, null, null,null);
		if(c != null){
			while(c.moveToNext() && c.isFirst()){
				values.clear();
				values.put(DBConstants.LOCAL_STATUS, 1);
				result = db.update(DBConstants.TABLE_LOCAL, values, DBConstants.LOCAL_ID+"=?", new String[]{String.valueOf(id)});
				AppLog.i(TAG, "本地数据更新为已上传，id:"+id+"; result:"+result);
			}
		}
		db.close();
		return result;
	}

	public synchronized int updateStatus(String data) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = helper.getWritableDatabase();
		int result = -1;
		Cursor c = db.query(DBConstants.TABLE_LOCAL, null, DBConstants.LOCAL_DATA+"=?",
				new String[]{data}, null, null,null);
		if(c != null){
			while(c.moveToNext() && c.isFirst()){
				values.clear();
				values.put(DBConstants.LOCAL_STATUS, 1);
				result = db.update(DBConstants.TABLE_LOCAL, values, DBConstants.LOCAL_DATA+"=?", new String[]{data});
				AppLog.i(TAG, "本地数据更新为已上传，data:"+data+"; result:"+result);
			}
		}
		db.close();
		return result;
	}
}
